<template>
  <div :class="{ show: state.show }" class="header-search flex items-center">
    <icon icon="svg-icon:search" class="mr-5px" @click.stop="click" />
    <el-select
      ref="headerSearchSelect"
      v-model="state.search"
      :remote-method="querySearch"
      filterable
      default-first-option
      remote
      placeholder="Search"
      class="header-search-select"
      @change="change"
    >
      <el-option
        v-for="item in state.options"
        :key="item.path"
        :value="item.path"
        :label="item.title?.join(' > ')"
      />
    </el-select>
  </div>
</template>

<script setup lang="ts">
import Fuse from 'fuse.js'
import { usePermissionStore } from '@/store/modules/permission'
import { ElSelect, ElOption } from 'element-plus'
import { Icon } from '@/components/base-icon'
import { onMounted, reactive, ref, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from '@/hooks/web/use-i18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import PyinMatch from 'pinyin-match'
const router = useRouter()
const { t } = useI18n()

function resolvePath(...paths) {
  const pathArr: string[] = []

  for (let path of paths) {
    const relativePath = path.replace(/^\//, '').replace(/\/$/, '')
    relativePath && pathArr.push(relativePath)
  }
  console.log(pathArr)

  return pathArr.join('/')
}

const state: {
  [x: string]: any
  search: string
  show: boolean
} = reactive({
  search: '',
  options: [],
  searchPool: [],
  show: false,
  fuse: null
})

const headerSearchSelect = ref()

function click() {
  state.show = !state.show
  if (state.show) {
    headerSearchSelect.value?.focus?.()
  }
}
function close() {
  headerSearchSelect.value?.blur?.()
  state.options = []
  state.show = false
  state.search = ''
}

function change(val) {
  router.push('/' + val)
  state.search = ''
  state.options = []
  nextTick(() => {
    state.show = false
  })
}
function initFuse(list) {
  console.log(list, 'list')
  state.fuse = new Fuse(list, {
    shouldSort: true,
    threshold: 0.4,
    location: 0,
    distance: 100,
    minMatchCharLength: 1,
    keys: [
      {
        name: 'title',
        weight: 0.7
      },
      {
        name: 'path',
        weight: 0.3
      }
    ]
  })
}
// Filter out the routes that can be displayed in the sidebar
// And generate the internationalized title
function generateRoutes(routes, basePath = '/', prefixTitle = []) {
  let res: any[] = []
  for (const router of routes) {
    // skip hidden router
    if (router.hidden) {
      continue
    }
    const data: {
      path: string
      title: any
    } = {
      path: resolvePath(basePath, router.path),
      title: [...prefixTitle]
    }
    if (router.meta && router.meta.title) {
      data.title = [...data.title, t(router.meta.title)]
      if (router.redirect !== 'noRedirect') {
        // only push the routes with title
        // special case: need to exclude parent router without redirect
        res.push(data)
      }
    }
    // recursive child routes
    if (router.children) {
      const tempRoutes = generateRoutes(router.children, data.path, data.title)
      if (tempRoutes.length >= 1) {
        res = [...res, ...tempRoutes]
      }
    }
  }
  return res
}

function getPyMatch(query) {
  return state.searchPool.filter((item) => {
    return PyinMatch.match(item.title.join('/'), query)
  })
}

function getFuseMath(query) {
  return state.fuse.search(query).map((data) => data.item)
}

function querySearch(query) {
  if (query !== '') {
    const isCn = useLocaleStoreWithOut().currentLocale.lang === 'zh-CN'
    state.options = /[a-zA-Z]/.test(query) && isCn ? getPyMatch(query) : getFuseMath(query)
  } else {
    state.options = []
  }
}

watch(
  () => state.searchPool,
  (list) => {
    initFuse(list)
  }
)

watch(
  () => state.show,
  (value) => {
    value
      ? document.body.addEventListener('click', close)
      : document.body.removeEventListener('click', close)
  }
)

onMounted(() => {
  state.searchPool = generateRoutes(usePermissionStore().getRouters)
})
</script>

<style lang="less" scoped>
.header-search {
  font-size: 0 !important;
  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }
  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    :deep(.el-input__inner) {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }
  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
